var

    app = require('../app'),
    template = require('../../modules/template'),
    swiper=false;

    getMobile();
    function getMobile(){
        $.ajax({
            url:"/callinfo/getMobile",
            method:"post",
            data:{
                caseId: $('[name="caseId"]').val(),
                callid: sessionStorage.getItem('calljumpInfo')?JSON.parse(sessionStorage.getItem('calljumpInfo')).callid:''
            },
            success:function(res){
                if(res.code==200){
                    if(res.data.length){
                        $('.phone-wrapper').html(template.render('phoneTpl',{
                            data: res.data
                        }));
                        if(!swiper){
                            swiper = new Swiper(".mySwiper", {
                                navigation: {
                                    nextEl: ".swiper-button-next",
                                    prevEl: ".swiper-button-prev",
                                },
                                observer: true,
                                // loop: true,
                            });
                        }
                        for(var i=0;i<res.data.length;i++){
                            res.data[i].caseid= $('[name="caseId"]').val();
                        }
                        $('.phone-dropdown').html(template.render('phoneTpl2',{
                            data: res.data
                        }));
                    }else{
                        $('.phone-wrapper').html('暂无电话数据');
                    }
                }else{
                    toastr.error(res.message);
                }
            },
            error: function(err){
                toastr.error('网络错误,请稍后重试');
            }
        })
    }

    /**
 * 指定日期增加n月
 * @param dateStr 指定日期
 * @param num 月
 * @param type 0:2023-01-30   1：2022-01-30 11:11:11
 * @returns {string}
 * @author: Leo
 */

    function commonAddMouth(dateStr, num, type) {
        var monthNum = 0;
        if (typeof num == "string") {
            monthNum = parseInt(num);
        } else {
            monthNum = num;
        }
        var date = new Date(dateStr);
        //获取原日
        var day = date.getDate();
        //获取原月份
        var month = date.getMonth();
        //设置增加月份
        date.setMonth(date.getMonth() + monthNum * 1, 1);
        //获取增加的后的月份
        var Jmonth = date.getMonth() + 1;
        //获取增加的后的年份
        var Jyear = date.getFullYear();
        if (Jmonth == 4 || Jmonth == 6 || Jmonth == 9 || Jmonth == 11) {
            //小月
            if (day > 30) {
                day = 30;
            }
        } else if (Jmonth == 2) {
            //2月判断是否闰年
            if ((Jyear % 4 == 0 && Jyear % 100 != 0) || Jyear % 400 == 0) {
                if (day > 29) {
                    day = 29;
                }
            }
            if (day > 28) {
                day = 28;
            }
        } else {
            //大月
            if (day > 31) {
                day = 31;
            }
        }
        var tHours = date.getHours();
        var tMinutes = date.getMinutes();
        var tSeconds = date.getSeconds();
        tHours = tHours < 10 ? "0" + tHours : tHours;
        tMinutes = tMinutes < 10 ? "0" + tMinutes : tMinutes;
        tSeconds = tSeconds < 10 ? "0" + tSeconds : tSeconds;
        Jmonth = doHandleMonth(Jmonth);
        day = doHandleMonth(day);
        if (type == "0") {
            return `${Jyear}-${Jmonth}-${day}`;
        }

        return `${Jyear}-${Jmonth}-${day} ${tHours}:${tMinutes}:${tSeconds}`;
    }

    /**
     *  日或月补0
     * @param month
     * @returns {string}
     */
    function doHandleMonth(month) {
        var m = month;
        if (month.toString().length == 1) {
            m = "0" + month;
        }
        return m;
    }


    $('body')
    .on('click','[data-fn="add-phone"]',function(){
        let newVal = $('[data-value="new-phone"]').val();
        if(!newVal){
            toastr.error('请输入号码');
            return false;
        }
        if(!(/^1[3,4,5,6,7,8,9][0-9]{9}$/.test(newVal))){
            toastr.error("手机号码有误，请重新输入");
            return false;
        }
        $.ajax({
            url:"/mediate/phoneAdd",
            method:"post",
            data:{
                caseId: $('[name="caseId"]').val(),
                telephone: newVal,
            },
            success:function(res){
                if(res.code==200){
                    toastr.success(res.message);
                    $('#new-phone-dialog').modal('hide');
                    setTimeout(function(){
                        getMobile();
                    },1500)
                }else{
                    toastr.error(res.message);
                }
            },
            error: function(err){
                toastr.error('网络错误,请稍后重试');
            }
        })
    })
    .on('click','[data-fn="delect-phone"]',function(){
        var that=$(this);
        $.confirm({
            title: '注意！',
            content: '确认删除该电话吗？',
            confirmButton: '确定',
            cancelButton: '取消',
            confirm: function(){
                $.ajax({
                    url:"/mediate/phoneDelete",
                    method:"post",
                    data:{
                        mobileId: that.parents('.ds-jc').next().find('.swiper-slide').eq(swiper.realIndex).find('[data-select="phone-update"]').attr('data-mobileid'),
                    },
                    success:function(res){
                        if(res.code==200){
                            toastr.success(res.message);
                            setTimeout(function(){
                                getMobile();
                            },1500)
                        }else{
                            toastr.error(res.message);
                        }
                    },
                    error: function(err){
                        toastr.error('网络错误,请稍后重试');
                    }
                })
            },
            cancel: function(){
                // alert('Canceled!')
            }
        });
    })
    .on('change','[data-select="phone-update"]',function(){
        $.ajax({
            url:"/mediate/phoneUpdate",
            method:"post",
            data:{
                mobileId: $(this).attr('data-mobileId'),
                mobileStatus: $(this).val(),
            },
            success:function(res){
                if(res.code==200){
                    toastr.success(res.message);
                }else{
                    toastr.error(res.message);
                }
            },
            error: function(err){
                toastr.error('网络错误,请稍后重试');
            }
        })
    })
    .on('click','[data-fn="add-plan"]',function(){
        let form= $(this).parents('form');

        let returnedMoney= form.find('[name="returnedMoney"]').val();
        let repaymentPeriods= form.find('[name="repaymentPeriods"]').val();
        let returnedDay= form.find('[name="returnedDay"]').val();

        if(!returnedMoney){
            toastr.error('请输入还款总额');
            return false;
        }
        if(!repaymentPeriods){
            toastr.error('请输入还款期数');
            return false;
        }
        $('.plan-box').html('');
        var date = new Date();
        var nowYear = date.getFullYear();
        if(date.getDate() > returnedDay){
            var nowMonth = date.getMonth() + 1;
        }else{
            var nowMonth = date.getMonth();
        }
        for(var i=0;i<repaymentPeriods;i++){
            var newDate='';
            if(i==0){
                newDate= commonAddMouth(nowYear+'-'+nowMonth+'-'+returnedDay,'1','0');
            }else{
                var nextDate= $('.plan-box').children(":last-child").find('[type="date"]').val();
                newDate= commonAddMouth(nextDate,'1','0');
            }
            var hml= `
                <div class="ds-ac-jc plan-list" style="margin-bottom:10px;">
                    <span class="col-sm-3">第${
                        i+1
                    }期</span>
                    <div class="col-sm-4">
                        <input type="date" class="form-control" name="returnedDetail[${i}][returnedTime]" value="${newDate}">
                    </div>
                    <div class="col-sm-4">
                        <input type="text" class="form-control" name="returnedDetail[${i}][returnedMoney]" value="${(returnedMoney/repaymentPeriods).toFixed(2)}" placeholder="请输入金额">
                    </div>
                </div>
            `;
            $('.plan-box').append(hml);
        }
        return false;
    })
    .on('click','[data-fn="save-plan"]',function(){
        $.ajax({
            url:"/mediate/addReturnedMoneyPlan",
            method:"post",
            data:$(this).parents('form').serialize(),
            success:function(res){
                if(res.code==200){
                    toastr.success(res.message);
                }else{
                    toastr.error(res.message);
                }
            },
            error: function(err){
                toastr.error('网络错误,请稍后重试');
            }
        })
    })
    .on('click','[data-fn="clear-plan"]',function(){
        $('.plan-box').html('');
    })
    .on('click','.switch-item',function(){
        let type=$(this).attr('data-type');
        if(type=='mediationLog'){
            $.ajax({
                url:"/mediate/getMediationLog",
                method:"post",
                data:{
                    caseId: $('[name="caseId"]').val(),
                },
                success:function(res){
                    if(res.code==200){
                        if(res.data.length){
                            var hml='';
                            $.each(res.data,function(index,val){
                                hml+=`
                                    <li class="sv-timeline-item">
                                        <div class="sv-timeline-item__tail"></div>
                                        <div class="sv-timeline-item__node sv-timeline-item__node--normal sv-timeline-item__node--">
                                            <div></div>
                                        </div>
                                        <div class="sv-timeline-item__wrapper">
                                            <div class="sv-timeline-item__timestamp is-bottom">${val.addTime}</div>
                                            <div class="sv-timeline-item__content">
                                                <div style="color:#666">${val.mediatorName}&nbsp;${val.type}&nbsp;${val.mobile}&nbsp;【${val.mediateResult}】</div>
                                    `;
                                if(val.nextTime){
                                    hml+=`<div style="margin-top: 5px;">联系计划：${val.nextTime}</div>`;
                                }
                                hml+=`<div style="margin-top: 5px;">${val.desc} </div>`;
                                if(val.fileName){
                                    hml+=`<div><audio controls="controls" src="${val.fileName}" style="width: 200px;height: 36px;margin-top: 10px;"></audio></div>`;
                                }
                                ` </div>
                                        </div>
                                    </li>
                                `;
                            })
                            $('.getMediationLog').html(hml);
                        }else{
                            $('.getMediationLog').html('<span>暂无数据</span>');
                        }
                    }else{
                        toastr.error(res.message);
                    }
                },
                error: function(err){
                    toastr.error('网络错误,请稍后重试');
                }
            })
        }else if(type=='sMSLog'){
            $.ajax({
                url:"/mediate/getSMSLog",
                method:"post",
                data:{
                    caseId: $('[name="caseId"]').val(),
                },
                success:function(res){
                    if(res.code==200){
                        if(res.data.length){
                            var hml='';
                            $.each(res.data,function(index,val){
                                hml+=`
                                    <li class="sv-timeline-item">
                                        <div class="sv-timeline-item__tail"></div>
                                        <div class="sv-timeline-item__node sv-timeline-item__node--normal sv-timeline-item__node--">
                                            <div></div>
                                        </div>
                                        <div class="sv-timeline-item__wrapper">
                                            <div class="sv-timeline-item__timestamp is-bottom">${val.sendTime }</div>
                                            <div class="sv-timeline-item__content">
                                                <div style="color:#666">${val.mediator}&nbsp;${val.mobile}【${val.scene}】${val.sendStatus}</div>
                                                <div style="margin-top: 5px;">${val.content} </div>
                                            </div>
                                        </div>
                                    </li>
                                `;
                            })
                            $('.getSMSLog').html(hml);
                        }else{
                            $('.getSMSLog').html('<span>暂无数据</span>');
                        }
                    }else{
                        toastr.error(res.message);
                    }
                },
                error: function(err){
                    toastr.error('网络错误,请稍后重试');
                }
            })
        }else if(type=='operateLog'){
            $.ajax({
                url:"/mediate/getOperateLog",
                method:"post",
                data:{
                    caseId: $('[name="caseId"]').val(),
                },
                success:function(res){
                    if(res.code==200){
                        if(res.data.length){
                            var hml='';
                            $.each(res.data,function(index,val){
                                hml+=`
                                    <li class="sv-timeline-item">
                                        <div class="sv-timeline-item__tail"></div>
                                        <div class="sv-timeline-item__node sv-timeline-item__node--normal sv-timeline-item__node--">
                                            <div></div>
                                        </div>
                                        <div class="sv-timeline-item__wrapper">
                                            <div class="sv-timeline-item__timestamp is-bottom">${val.createTime }</div>
                                            <div class="sv-timeline-item__content">
                                                <div style="color:#666">${val.operationName}&nbsp;${val.operationContent}</div>
                                                <div style="margin-top: 5px;">${val.remark} </div>
                                            </div>
                                        </div>
                                    </li>
                                `;
                            })
                            $('.getOperateLog').html(hml);
                        }else{
                            $('.getOperateLog').html('<span>暂无数据</span>');
                        }
                    }else{
                        toastr.error(res.message);
                    }
                },
                error: function(err){
                    toastr.error('网络错误,请稍后重试');
                }
            })
        }else if(type=='returnedPlan'){
            $.ajax({
                url:"/mediate/getReturnedPlan",
                method:"post",
                data:{
                    caseId: $('[name="caseId"]').val(),
                },
                success:function(res){
                    if(res.code==200){
                        if(res.data.length){
                            var hml='';
                            $.each(res.data,function(index,val){
                                hml+=`
                                    <tr>
                                        <td>${val.term}</td>
                                        <td>${val.repaymentDate}</td>
                                        <td>${val.repayAmount}</td>
                                        <td>${val.status}</td>
                                    </tr>
                                    `;
                            })
                            $('.getReturnedPlan').html(hml);
                        }else{
                            $('.getReturnedPlan').html('<span>暂无数据</span>');
                        }
                    }else{
                        toastr.error(res.message);
                    }
                },
                error: function(err){
                    toastr.error('网络错误,请稍后重试');
                }
            })
        }
    })
    .on('click','[data-fn="addMediationLog"]',function(){
        var _this=$(this);
        if(_this.attr('disabled')) return;
        _this.attr('disabled',true);
        $.ajax({
            url:"/mediate/addMediationLog",
            method:"post",
            data:$(this).parents('form').serialize(),
            success:function(res){
                if(res.code==200){
                    toastr.success('保存成功');
                    _this.next().click();
                }else{
                    toastr.error(res.message);
                }
                _this.removeAttr('disabled',true);
            },
            error: function(err){
                toastr.error('网络错误,请稍后重试');
                _this.removeAttr('disabled',true);
            }
        })
        return false;
    })
    .on('click','[data-fn="switch-page"]',function(){
        let _this=$(this);
        let type=_this.attr('data-type');
        if(_this.attr('disabled')) return;
        _this.attr('disabled',true)
        $.ajax({
            url:"/mediate/getNextId",
            method:"post",
            data:{
                caseId: $('[name="caseId"]').val(),
                direction: type,
                fieldType: $('[name="fieldType"]').val(),
            },
            success:function(res){
                console.log(11111)
                console.log(res)
                try{
                    console.log(res.data)
                }catch(ee){

                }
                if(res.code==200){
                    window.location.replace('/mediate/detail?caseId='+res.data.caseId)
                }else{
                    if(type=='next'){
                        toastr.error('没有下一个了');
                    }else{
                        toastr.error('没有上一个了');
                    }
                }
                _this.removeAttr('disabled',true);
            },
            error: function(err){
                toastr.error('网络错误,请稍后重试');
                _this.removeAttr('disabled',true);
            }
        })
    })
    .on('change','[data-select="custom-select"]',function(){
        $.ajax({
            url:"/mediate/updateAttribute",
            method:"post",
            data:{
                caseId: $('[name="caseId"]').val(),
                attribute: $(this).attr('name'),
                attributeVal: $(this).val(),
            },
            success:function(res){
                if(res.code==200){
                    toastr.success(res.message);
                }else{
                    toastr.error(res.message);
                }
            },
            error: function(err){
                toastr.error('网络错误,请稍后重试');
            }
        })
     })
     //mouseenter
    .on('click','[data-hover="call"],.phone-dropdown',function(){
        $('.phone-dropdown').show();
    })
    .on('mouseleave','[data-ele="btn-box"]',function(){
        $('.phone-dropdown').hide();
    })
